<template>
  <!-- 标准检验类型表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="500px"
    draggable
    @close="closeDialog"
  >
    <el-form
      v-show="!props.isReadonly"
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="160"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="检验类型编码" prop="checkTypeCode">
            <el-input
              v-model="formData.checkTypeCode"
              placeholder="请输入检验单类型编码"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="检验类型名称" prop="checkTypeName">
            <el-input
              v-model="formData.checkTypeName"
              placeholder="请输入检验单类型名称"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="操作类型" prop="opeTypeCode">
            <el-select
              style="width: 100%"
              v-model="formData.opeTypeCode"
              placeholder="请选择操作类型"
              clearable
              :disabled="isBind"
              @change="changeOpeType"
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList(
                  'CheckOperateType'
                )"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="事务类型" prop="effectTypeCode">
            <el-select
              style="width: 100%"
              v-model="formData.effectTypeCode"
              placeholder="请选择事务类型"
              clearable
              :disabled="isBind"
            >
              <el-option
                v-for="item in effectTypeCodeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="检验部门" prop="checkDepId">
            <SelectOriganizationDangerGrant
              @change-data="getSelectData"
              :isCheckStrictly="true"
              :isMultiple="false"
              :disabled="false"
              :data="dataObject('检验部门')"
              :selectData="formData.checkDepId"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-descriptions
      v-show="props.isReadonly"
      class="margin-top w-full"
      title=""
      :column="1"
      size="large"
      border
    >
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">检验类型编码</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.checkTypeCode || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">检验类型名称</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.checkTypeName || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">操作类型</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ useDictionary("CheckOperateType", formData.opeTypeCode) || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">事务类型</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ getEffectTypeCode(formData) }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">检验部门</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.checkDepName || "" }}
        </div>
      </el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { useDictionary } from "@/utils/useTable";
import { checkCommon } from "@/views/qms/checkHook/checkCommon"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QMSQMSCHECKTYPEADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const isBind = ref(false);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  checkTypeName: [
    {
      required: true,
      message: "请输入检验单类型名称",
      trigger: ["blur", "change"],
    },
    {
      min: 1,
      max: 50,
      message: "长度在 1 到 50 个字符",
      trigger: ["blur", "change"],
    },
  ],
  checkTypeCode: [
    {
      required: true,
      message: "请输入检验单类型编码",
      trigger: ["blur", "change"],
    },
    {
      min: 1,
      max: 50,
      message: "长度在 1 到 50 个字符",
      trigger: ["blur", "change"],
    },
  ],
  effectTypeCode: [
    {
      required: true,
      message: "请选择事务类型",
      trigger: ["blur", "change"],
    },
  ],
  opeTypeCode: [
    {
      required: true,
      message: "请选择操作类型",
      trigger: ["blur", "change"],
    },
  ],
  checkDepId: [
    {
      required: true,
      message: "请选择检验部门",
      trigger: ["blur", "change"],
    },
    {
      min: 1,
      max: 32,
      message: "长度在 1 到 32 个字符",
      trigger: ["blur", "change"],
    },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  checkTypeName: "",
  checkTypeCode: "",
  effectTypeCode: "",
  opeTypeCode: "",
  checkDepName: "",
  checkDepId: "",
  checkDepCode: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
});

const { changeOpeType, getEffectTypeCode, effectTypeCodeList } = checkCommon(
  ref(formData)
);
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        checkTypeName,
        checkTypeCode,
        bind,
        effectTypeCode,
        opeTypeCode,
        checkDepName,
        checkDepId,
        checkDepCode,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      } = newVal;
      changeOpeType(opeTypeCode);
      isBind.value = bind;
      Object.assign(formData, {
        id,
        version,
        checkTypeName,
        checkTypeCode,
        effectTypeCode,
        opeTypeCode,
        checkDepName,
        checkDepId,
        checkDepCode,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
  effectTypeCodeList.value = [];
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.checkTypeName = "";
  formData.checkTypeCode = "";
  formData.effectTypeCode = "";
  formData.opeTypeCode = "";
  formData.checkDepName = "";
  formData.checkDepId = "";
  formData.checkDepCode = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
  isBind.value = false;
}

const loading = ref(false);

/** 标准检验类型保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/qms/qmschecktype/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

// 组织机构 placeholder值
const dataObject = (name: string) => {
  return {
    name,
    defaultProps: {
      children: "nodes",
      label: "organizationName",
      value: "id",
    },
    api: "/system/sysOrganization/getUsableTree",
  };
};

/** 选择组织机构并赋值Name   start **/
function getSelectData(data: any) {
  formData.checkDepName = data.organizationName ?? "";
  formData.checkDepCode = data.organizationCode ?? "";
  formData.checkDepId = data.id ?? "";
}
</script>
